<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>注册页面</title>
  <link rel="stylesheet" href="../lib/layui/css/layui.css">
  <link rel="stylesheet" href="../css/base.css">
  <link rel="stylesheet" href="../css/form.css">
</head>

<body>
  <div class="header container">注册页面</div>
  <form class="layui-form">
    <span class="error">用户名已存在，请更换！</span>
    <label>
      用户名：&nbsp;&nbsp; <input type="text" name="username" lay-verify="required" class="username">
    </label>
    <label>
      密&nbsp;&nbsp;&nbsp;码： &nbsp;&nbsp;<input type="text" name="password" lay-verify="required" class="password">
    </label>
    <label>
      确认密码： &nbsp;&nbsp;<input type="text" name="rpassword" class="rpassword">
    </label>
    <label>
      昵&nbsp;&nbsp;&nbsp;称：&nbsp;&nbsp; <input type="text" name="nickname" lay-verify="required" class="nickname">
    </label>
    <p>已有账号，<a href="./login.html">直接登录</a></p>
    <button lay-submit lay-filter="login">注册</button>
  </form>
  <script type="module">
    import '../lib/axios.js'
    import '../lib/layui/layui.js'
    layui.use(['form'], function () {
      var form = layui.form;
      var $ = layui.$;
      var layer = layui.layer;

      // 表单验证
      form.verify({
        required: function (value, item) {
          if (!value) {
            return '该项为必填项';
          }
        }
      });

      // 登录提交事件
      form.on('submit(login)', function (data) {
        var username = data.field.username;
        var password = data.field.password;
        var rpassword = data.field.rpassword;
        var nickname = data.field.nickname;

        if (password !== rpassword) {
          layer.msg('两次密码不一致', { icon: 0 })
          return false;
        }

        axios.post('http://localhost:9000/users/register', data.field)
          .then(function (response) {
            if (response.data.code === 1) {
              layer.msg(response.data.message, { icon: 1 });
              location.href = './login.html'
            } else {
              layer.msg(response.data.message, { icon: 0 })
            }
          })
          .catch(function (error) {
            layer.msg('请求出错');
          });

        return false; // 阻止表单默认提交
      });
    });
  </script>
</body>

</html>